<?php
require_once("../globals.php");
require_once($GLOBALS['fileroot'] . "/library/acl.inc");
require_once($GLOBALS['fileroot'] . "/custom/code_types.inc.php");
require_once($GLOBALS['fileroot'] . "/library/patient.inc");
require_once($GLOBALS['fileroot'] . "/library/lists.inc");

// This array defines the list of primary documents that may be
// chosen.  Each element value is an array of 3 values:
//
// * Name to appear in the navigation table
// * Usage: 0 = global, 1 = patient-specific, 2 = encounter-specific
// * The URL relative to the interface directory
//

$primary_docs = array(
    'ros' => array(xl('Roster'), 0, 'reports/players_report.php?embed=1'),
    'cal' => array(xl('Calendar'), 0, 'main/calendar/index.php?module=PostCalendar&viewtype=month&func=view'),
    'app' => array(xl('Portal Activity'), 0, '../myportal/index.php'),
    'msg' => array(xl('Messages'), 0, 'main/messages/messages.php?form_active=1'),
    'pwd' => array(xl('Password'), 0, 'usergroup/user_info.php'),
    'prf' => array(xl('Preferences'), 0, 'super/edit_globals.php?mode=user'),
    'adm' => array(xl('Admin'), 0, 'usergroup/admin_frameset.php'),
    'rep' => array(xl('Reports'), 0, 'reports/index.php'),
    'ono' => array(xl('Ofc Notes'), 0, 'main/onotes/office_comments.php'),
    'fax' => array(xl('Fax/Scan'), 0, 'fax/faxq.php'),
    'adb' => array(xl('Addr Bk'), 0, 'usergroup/addrbook_list.php'),
    'ort' => array(xl('Proc Cat'), 0, 'orders/types.php'),
    'orb' => array(xl('Proc Bat'), 0, 'orders/orders_results.php?batch=1'),
    'cht' => array(xl('Chart Trk'), 0, '../custom/chart_tracker.php'),
    'imp' => array(xl('Import'), 0, '../custom/import.php'),
    'bil' => array(xl('Billing'), 0, 'billing/billing_report.php'),
    'sup' => array(xl('Superbill'), 0, 'patient_file/encounter/superbill_custom_full.php'),
    'aun' => array(xl('Authorizations'), 0, 'main/authorizations/authorizations.php'),
    'new' => array(xl('New Pt'), 0, 'new/new.php'),
    'ped' => array(xl('Patient Education'), 0, 'reports/patient_edu_web_lookup.php'),
    'lab' => array(xl('Check Lab Results'), 0, 'orders/lab_exchange.php'),
    'dem' => array(xl('Patient'), 1, "patient_file/summary/demographics.php"),
    'his' => array(xl('History'), 1, 'patient_file/history/history.php'),
    'ens' => array(xl('Visit History'), 1, 'patient_file/history/encounters.php'),
    'nen' => array(xl('Create Visit'), 1, 'forms/newpatient/new.php?autoloaded=1&calenc='),
    'pre' => array(xl('Rx'), 1, 'patient_file/summary/rx_frameset.php'),
    'iss' => array(xl('Issues'), 1, 'patient_file/summary/stats_full.php?active=all'),
    'imm' => array(xl('Immunize'), 1, 'patient_file/summary/immunizations.php'),
    'doc' => array(xl('Documents'), 1, '../controller.php?document&list&patient_id={PID}'),
    'orp' => array(xl('Proc Pending Rev'), 1, 'orders/orders_results.php?review=1'),
    'orr' => array(xl('Proc Res'), 1, 'orders/orders_results.php'),
    'prp' => array(xl('Pt Report'), 1, 'patient_file/report/patient_report.php'),
    'prq' => array(xl('Pt Rec Request'), 1, 'patient_file/transaction/record_request.php'),
    'pno' => array(xl('Pt Notes'), 1, 'patient_file/summary/pnotes.php'),
    'tra' => array(xl('Transact'), 1, 'patient_file/transaction/transactions.php'),
    'sum' => array(xl('Summary'), 1, 'patient_file/summary/summary_bottom.php'),
    'enc' => array(xl('Encounter'), 2, 'patient_file/encounter/encounter_top.php'),
    'erx' => array(xl('e-Rx'), 1, 'eRx.php'),
    'err' => array(xl('e-Rx Renewal'), 1, 'eRx.php?page=status'),
    'pay' => array(xl('Payment'), 1, '../patient_file/front_payment.php')
);
$primary_docs['npa'] = array(xl('Batch Payments'), 0, 'billing/new_payment.php');
if ($GLOBALS['use_charges_panel'] || $GLOBALS['concurrent_layout'] == 2) {
    $primary_docs['cod'] = array(xl('Charges'), 2, 'patient_file/encounter/encounter_bottom.php');
}

// This section decides which navigation items will not appear.

$element='';

$disallowed = array();

$disallowed['adm'] = !(acl_check('admin', 'calendar') ||
        acl_check('admin', 'database') || acl_check('admin', 'forms') ||
        acl_check('admin', 'practice') || acl_check('admin', 'users') ||
        acl_check('admin', 'acl') || acl_check('admin', 'super') ||
        acl_check('admin', 'superbill'));

$disallowed['bil'] = !(acl_check('acct', 'rep') || acl_check('acct', 'eob') ||
        acl_check('acct', 'bill'));

$tmp = acl_check('patients', 'demo');
$disallowed['new'] = !($tmp == 'write' || $tmp == 'addonly');

$disallowed['fax'] = !($GLOBALS['enable_hylafax'] || $GLOBALS['enable_scanner']);

$disallowed['ros'] = !$GLOBALS['athletic_team'];

$disallowed['iss'] = !((acl_check('encounters', 'notes') == 'write' ||
        acl_check('encounters', 'notes_a') == 'write') &&
        acl_check('patients', 'med') == 'write');

$disallowed['imp'] = $disallowed['new'] ||
        !is_readable("$webserver_root/custom/import.php");

$disallowed['cht'] = !is_readable("$webserver_root/custom/chart_tracker.php");

$disallowed['pre'] = !(acl_check('patients', 'med'));

check_messages();

// Helper functions for treeview generation.
function genTreeLink2($frame, $name, $title, $mono = false) {
    global $primary_docs, $disallowed;
    if (empty($disallowed[$name])) {
        $id = $name . $primary_docs[$name][1];
        echo "<li><a href='' id='$id' onclick=\"";
        if ($mono) {
            if ($frame == 'RTop')
                echo "forceSpec(true,false);";
            else
                echo "forceSpec(false,true);";
        }
        echo "return ajaxRequest('$id','$frame','" .
        $primary_docs[$name][2] . "')\">" . $title . ($name == 'msg' ? ' <span id="reminderCountSpan" class="bold"></span>' : '') . "</a></li>";
    }
}

function genMiscLink2($frame, $name, $level, $title, $url, $mono = false) {
    global $disallowed, $module;
    if (empty($disallowed[$name])) {
        $id = $name . $level;
        echo "<li><a href='' id='$id' onclick=\"";
        if ($mono) {
            if ($frame == 'RTop')
                echo "forceSpec(true,false);";
            else
                echo "forceSpec(false,true);";
        }
        echo "return ajaxRequest('$id','$frame','" .
        $url . "')\">" . $title . "</a></li>";
    }
	$parts = explode("/", $url);
	if($parts[1]=='drugs'){
		$module = 'drugs';
	}else{
		$module = 'calendar';
	}
	
}

function check_messages(){
		global $element;
		$user = $_SESSION['authUserID'];
		$query = "SELECT * FROM users WHERE id = $user";
		$res = sqlStatement($query);
		$row = sqlFetchArray($res);
		$username = $row['username'];
		
		$query = "SELECT count(*) num FROM pnotes WHERE assigned_to = \"$username\" AND message_status = 'nuevo' AND deleted=0";
		$res = sqlStatement($query);
		$row = sqlFetchArray($res);
		$result = $row['num'];
		
		if ($result >= 1){
			$element .= '<span id="reminder_counter">';
			$element .= '<span id="red_circle">'.$result.'</span>';
			
			$element .= '</span>';
		}else{
			$element .= '<span class="reminder_counter">';
			
			$element .= '</span>';
		}
}

function set_red(){
		$user = $_SESSION['authUserID'];
		$query = "SELECT * FROM users WHERE id = $user";
		$res = sqlStatement($query);
		$row = sqlFetchArray($res);
		$username = $row['username'];
		
		$query = "UPDATE pnotes SET status = 'Leido' WHERE assigned_to = $username AND message_status = 'nuevo'";
		sqlStatement($query);
		
}

function genPopLink2($title, $url, $linkid = '') {
    echo "<li><a href='' ";
    if ($linkid)
        echo "id='$linkid' ";
    echo "onclick=\"return repPopup('$url')\"" .
    ">" . $title . "</a></li>";
}

/*print_r($_REQUEST);*/
?>
<html>
    <head>
	
        <script language='JavaScript'>

            //valida si ha nuevos mensajes de inbox interno
            function getReminderCount() {
                top.restoreSession();
                // Send the skip_timeout_reset parameter to not count this as a manual entry in the
                //  timing out mechanism in SAC.
                $.post("<?php echo $GLOBALS['webroot']; ?>/library/ajax/dated_reminders_counter.php",
                        {skip_timeout_reset: "1"},
                function(data) {
                    $("#reminderCountSpan").html(data);
                    // run updater every 60 seconds 
                    var repeater = setTimeout("getReminderCount()", 60000);
                });
            }
	
	
	
	function ReminderBatch(processType) {
	   //Hide the buttons and show the processing animation
	   $("#process_button").hide();
	   $("#process_send_button").hide();
	   $("#processing").show();

	   top.restoreSession();
	   $.get("<?php echo $GLOBALS['webroot']; ?>/library/ajax/collect_new_report_id.php",
		 function(data){
		   // Set the report id in page form
		   $("#form_new_report_id").attr("value",data);

		   // Start collection status checks
		   collectStatus($("#form_new_report_id").val());

		   // Run the report
		   top.restoreSession();
		   $.post("<?php echo $GLOBALS['webroot']; ?>/library/ajax/execute_pat_reminder.php",
			 {process_type: processType,
			  execute_report_id: $("#form_new_report_id").val()
			 });
	   });

		return false;
	}
	
	 function collectStatus(report_id) {
   // Collect the status string via an ajax request and place in DOM at timed intervals
   top.restoreSession();
   // Do not send the skip_timeout_reset parameter, so don't close window before report is done.
   $.post("<?php echo $GLOBALS['webroot']; ?>/library/ajax/status_report.php",
     {status_report_id: report_id},
     function(data){
       if (data == "PENDING") {
         // Place the pending string in the DOM
         $('#status_span').replaceWith("<span id='status_span'><?php echo xlt("Preparing To Run Report"); ?></span>");
       }
       else if (data == "COMPLETE") {
         // Go into the results page
         top.restoreSession();
         link_report = "patient_reminders.php?mode=admin&patient_id=";
         window.open(link_report,'_self',false);
       }
       else {
         // Place the string in the DOM
         $('#status_span').replaceWith("<span id='status_span'>"+data+"</span>");
       }
   });
   // run status check every 10 seconds
   var repeater = setTimeout("collectStatus("+report_id+")", 10000);
 }
	

            $(document).ready(function() {

                $('#msg0').click(function(e) {
					$.post( "<?php echo $GLOBALS['webroot']; ?>/interface/main/messages/read_messages.php" );
					$("#reminder_counter").remove();
				});
				
                $('#profile').click(function(e) {
                    e.preventDefault();
                        $.fancybox({
                        href: this.href,
                        autoSize: true,
                        type: 'iframe',
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }
                    }); // fancybox	
                }); // click
                getReminderCount();//
                parent.loadedFrameCount += 1;

                destino = convertURL("<?php
				if (isset($_REQUEST['destino']))
					echo $_REQUEST['destino'];
				else
					echo '';
				?>");
                                        destino1 = "<?php
				if (isset($_REQUEST['destino']))
					echo $_REQUEST['destino'];
				else
					echo '';
				?>";
                                        //alert(destino1);
								nombre = "<?php
				if (isset($_REQUEST['pname']))
					echo $_REQUEST['pname'];
				else
					echo '';
				?>";

								pacienteId = "<?php
				if (isset($_REQUEST['pid']))
					echo $_REQUEST['pid'];
				else
					echo '';
				?>";

								identificacion = "<?php
				if (isset($_REQUEST['pubpid']))
					echo $_REQUEST['pubpid'];
				else
					echo '';
				?>";
				if (destino !== ''){
					if(destino1 =='reports/patient_list.php'){
                                                
						form_refresh = "<?php
						if (isset($_REQUEST['form_refresh']))
							echo $_REQUEST['form_refresh'];
						else
							echo '';
						?>";
						
						form_from_date = "<?php
						if (isset($_REQUEST['form_from_date']))
							echo $_REQUEST['form_from_date'];
						else
							echo '';
						?>";
						
						form_to_date = "<?php
						if (isset($_REQUEST['form_to_date']))
							echo $_REQUEST['form_to_date'];
						else
							echo '';
						?>";
										
						form_csvexport = "<?php
						if (isset($_REQUEST['form_csvexport']))
							echo $_REQUEST['form_csvexport'];
						else
							echo '';
						?>";
                                                form_provider = "<?php
						if (isset($_REQUEST['form_provider']))
							echo $_REQUEST['form_provider'];
						else
							echo '';
						?>";                
                                                                
						$("#info").load(destino, {
						   form_refresh: form_refresh, 
						   form_from_date: form_from_date, 
						   form_to_date: form_to_date, 
						   form_csvexport: form_csvexport,
                                                   form_provider: form_provider
					   });
					}else if(destino =='/interface/reports/prescriptions_report.php'){
						form_refresh = "<?php
						if (isset($_REQUEST['form_refresh']))
							echo $_REQUEST['form_refresh'];
						else
							echo '';
						?>";
						
						form_from_date = "<?php
						if (isset($_REQUEST['form_from_date']))
							echo $_REQUEST['form_from_date'];
						else
							echo '';
						?>";
						
						form_to_date = "<?php
						if (isset($_REQUEST['form_to_date']))
							echo $_REQUEST['form_to_date'];
						else
							echo '';
						?>";
										
						form_facility = "<?php
						if (isset($_REQUEST['form_facility']))
							echo $_REQUEST['form_facility'];
						else
							echo '';
						?>";
						
						form_patient_id = "<?php
						if (isset($_REQUEST['form_patient_id']))
							echo $_REQUEST['form_patient_id'];
						else
							echo '';
						?>";
						
						form_drug_name = "<?php
						if (isset($_REQUEST['form_drug_name']))
							echo $_REQUEST['form_drug_name'];
						else
							echo '';
						?>";
						
						form_lot_number = "<?php
						if (isset($_REQUEST['form_lot_number']))
							echo $_REQUEST['form_lot_number'];
						else
							echo '';
						?>";
						$("#info").load(destino, {
						   form_refresh: form_refresh, 
						   form_from_date: form_from_date, 
						   form_to_date: form_to_date, 
						   form_facility: form_facility,
						   form_patient_id: form_patient_id,
						   form_drug_name: form_drug_name,
						   form_lot_number: form_lot_number
					   });
					}else if(destino =='/interface/reports/clinical_reports.php'){
						form_refresh = "<?php
						if (isset($_REQUEST['form_refresh']))
							echo $_REQUEST['form_refresh'];
						else
							echo '';
						?>";
						
						facility = "<?php
						if (isset($_REQUEST['facility']))
							echo $_REQUEST['facility'];
						else
							echo '';
						?>";
						
						date_from = "<?php
						if (isset($_REQUEST['date_from']))
							echo $_REQUEST['date_from'];
						else
							echo '';
						?>";
											
						date_to = "<?php
						if (isset($_REQUEST['date_to']))
							echo $_REQUEST['date_to'];
						else
							echo '';
						?>";
										
						patient_id = "<?php
						if (isset($_REQUEST['patient_id']))
							echo $_REQUEST['patient_id'];
						else
							echo '';
						?>";
						
						age_to = "<?php
						if (isset($_REQUEST['age_to']))
							echo $_REQUEST['age_to'];
						else
							echo '';
						?>";
											
						age_from = "<?php
						if (isset($_REQUEST['age_from']))
							echo $_REQUEST['age_from'];
						else
							echo '';
						?>";
						
						form_diagnosis = "<?php
						if (isset($_REQUEST['form_diagnosis']))
							echo $_REQUEST['form_diagnosis'];
						else
							echo '';
						?>";
						
						gender = "<?php
						if (isset($_REQUEST['gender']))
							echo $_REQUEST['gender'];
						else
							echo '';
						?>";
						
						form_drug_name = "<?php
						if (isset($_REQUEST['form_drug_name']))
							echo $_REQUEST['form_drug_name'];
						else
							echo '';
						?>";
						
						race = "<?php
						if (isset($_REQUEST['race']))
							echo $_REQUEST['race'];
						else
							echo '';
						?>";
						
						ethnicity = "<?php
						if (isset($_REQUEST['ethnicity']))
							echo $_REQUEST['ethnicity'];
						else
							echo '';
						?>";
						
						form_lab_results = "<?php
						if (isset($_REQUEST['form_lab_results']))
							echo $_REQUEST['form_lab_results'];
						else
							echo '';
						?>";
						
						type = "<?php
						if (isset($_REQUEST['type']))
							echo $_REQUEST['type'];
						else
							echo '';
						?>";
						
						form_service_codes = "<?php
						if (isset($_REQUEST['form_service_codes']))
							echo $_REQUEST['form_service_codes'];
						else
							echo '';
						?>";
						
						$("#info").load(destino, {
						   form_refresh: form_refresh, 
						   facility: facility, 
						   date_from: date_from, 
						   date_to: date_to,
						   patient_id: patient_id,
						   age_to: age_to,
						   age_from: age_from,
						   form_diagnosis: form_diagnosis,
						   gender: gender,
						   form_drug_name: form_drug_name,
						   race: race,
						   ethnicity: ethnicity,
						   form_lab_results: form_lab_results,
						   type: type,
						   form_service_codes: form_service_codes
					   });
					}else if(destino =='/interface/reports/appointments_report.php'){
						form_refresh = "<?php
						if (isset($_REQUEST['form_refresh']))
							echo $_REQUEST['form_refresh'];
						else
							echo '';
						?>";
						
						form_from_date = "<?php
						if (isset($_REQUEST['form_from_date']))
							echo $_REQUEST['form_from_date'];
						else
							echo '';
						?>";
						
						form_to_date = "<?php
						if (isset($_REQUEST['form_to_date']))
							echo $_REQUEST['form_to_date'];
						else
							echo '';
						?>";
										
						form_facility = "<?php
						if (isset($_REQUEST['form_facility']))
							echo $_REQUEST['form_facility'];
						else
							echo '';
						?>";
						
						form_provider = "<?php
						if (isset($_REQUEST['form_provider']))
							echo $_REQUEST['form_provider'];
						else
							echo '';
						?>";
						
						form_orderby = "<?php
						if (isset($_REQUEST['form_orderby']))
							echo $_REQUEST['form_orderby'];
						else
							echo '';
						?>";
						
						patient = "<?php
						if (isset($_REQUEST['patient']))
							echo $_REQUEST['patient'];
						else
							echo '';
						?>";
						$("#info").load(destino, {
						   form_refresh: form_refresh, 
						   form_from_date: form_from_date, 
						   form_to_date: form_to_date, 
						   form_facility: form_facility,
						   form_provider: form_provider,
						   form_orderby: form_orderby,
						   patient: patient
					   });
					}else if(destino =='/interface/reports/inventory_list.php'){
						form_action = "<?php
						if (isset($_REQUEST['form_action']))
							echo $_REQUEST['form_action'];
						else
							echo '';
						?>";
						
						form_days = "<?php
						if (isset($_REQUEST['form_days']))
							echo $_REQUEST['form_days'];
						else
							echo '';
						?>";
						
						$("#info").load(destino, {
						   form_action: form_action, 
						   form_days: form_days
					   });
					}else if(destino1=='reports/clinicos_reports.php'){
                                            
                                            form_refresh = "<?php
						if (isset($_REQUEST['form_refresh']))
							echo $_REQUEST['form_refresh'];
						else
							echo '';
						?>";
                                                                
                                                form_facility = "<?php
						if (isset($_REQUEST['form_facility']))
							echo $_REQUEST['form_facility'];
						else
							echo '';
						?>";
                                                                form_from_date = "<?php
						if (isset($_REQUEST['form_from_date']))
							echo $_REQUEST['form_from_date'];
						else
							echo '';
						?>";
						
						form_to_date = "<?php
						if (isset($_REQUEST['form_to_date']))
							echo $_REQUEST['form_to_date'];
						else
							echo '';
						?>";
                                                                form_diagnosis = "<?php
						if (isset($_REQUEST['form_diagnosis']))
							echo $_REQUEST['form_diagnosis'];
						else
							echo '';
						?>";
                                                $("#info").load(destino, {
						   form_refresh:form_refresh,
                                                   form_facility:form_facility,
                                                   form_from_date:form_from_date,
                                                   form_to_date:form_to_date,
                                                   form_diagnosis:form_diagnosis
                                                   
                                                   
					   });
                                        }
					else{
						$("#info").load(destino);
					}
				}
                if (pacienteId !== '') {
                    var str = '<a href=\'javascript:;\' onclick="loadPatient(' + pacienteId + '); return false;" title="PID = ' + pacienteId + '"><b>' + nombre + ' (' + identificacion + ')</b></a>';
                    $("#current_patient").html(str);
                    $("#current_encounter").html('<b><?php xl('None', 'e'); ?></b>');
                    active_pid = pacienteId;
                    active_encounter = 0;
                    //if (frname) reloadPatient(frname);
                    $('#current_patient_block').show();
                    var encounter_block = $('#current_encounter_block');
                    $(encounter_block).hide();
                }
            })
            // end of tajemo work dated reminders counter

            // Master values for current pid and encounter.
            var active_pid = 0;
            var active_encounter = 0;

            function loadPatient(pid) {
                $("#info").load("../patient_file/summary/demographics.php?set_pid=" + pid);
            }
            // Load the specified url into the specified frame (RTop or RBot).
            // The URL provided must be relative to interface.
            function loadFrame(fname, frame, url) {
                top.restoreSession();
                var i = url.indexOf('{PID}');
                if (i >= 0)
                    url = url.substring(0, i) + active_pid + url.substring(i + 5);
                top.frames[frame].location = '<?php echo "$web_root/interface/" ?>' + url;
                if (frame == 'RTop')
                    topName = fname;
                else
                    botName = fname;
            }

            var destino;
            // Load the specified url into a frame to be determined, with the specified
            // frame as the default; the url must be relative to interface.
            function ajaxRequest(fname, frame, url) {
                var usage = fname.substring(3);
                if (active_pid == 0 && usage > '0') {
                    alert('<?php xl('You must first select or add a patient.', 'e') ?>');
                    return false;
                }
                if (active_encounter == 0 && usage > '1') {
                    alert('<?php xl('You must first select or create an encounter.', 'e') ?>');
                    return false;
                }
                var f = document.forms[0];
                top.restoreSession();
                var i = url.indexOf('{PID}');
                if (i >= 0)
                    url = url.substring(0, i) + active_pid + url.substring(i + 5);

                destino = '<?php echo "$web_root/interface/" ?>' + url;

                $('#destino').val(url);
				

				
                $('#nombre').val(nombre);
                $('#pacienteId').val(pacienteId);
                $('#identificacion').val(identificacion);

//                if( typeof nombre !== "undefined" )
//                    alert(nombre);
                var f = document.forms[1];
                f.submit();

                return false;
            }
			
			function loadReport(url) {
                $("#info").load("../reports/" + url);
            }

            function convertURL(url) {
                var i = url.indexOf('{PID}');
                if (i >= 0)
                    url = url.substring(0, i) + active_pid + url.substring(i + 5);

                return '<?php echo "$web_root/interface/" ?>' + url;
            }

            // This is called by the search.php (Filter) window.
            function processFilter(fieldString, serviceCode) {
                var f = document.forms[0];
                document.getElementById('searchFields').value = fieldString;
                f.search_service_code.value = serviceCode;
                findPatient("Filter");
                f.search_service_code.value = '';
                my_window.close();
            }

            // Process the click to find a patient by name, id, ssn or dob.
            function findPatient(findby) {
                var f = document.forms[0];
                if (!f.cb_top.checked) {
                    f.cb_top.checked = true;
                    toggleFrame(1);
                }
                f.findBy.value = findby;
                setRadio('rb_top', 'dem');
                top.restoreSession();
                document.find_patient.submit();
            }

            // Helper function to set the contents of a div.
            function setSomeContent(id, content, doc) {
                if (doc.getElementById) {
                    var x = doc.getElementById(id);
                    x.innerHTML = '';
                    x.innerHTML = content;
                }
                else if (doc.all) {
                    var x = doc.all[id];
                    x.innerHTML = content;
                }
            }

            function setDivContent(id, content) {
                setSomeContent(id, content, document);
            }

            function setTitleContent(id, content) {
                setSomeContent(id, content, parent.Title.document);
            }

            // This is called automatically when a new patient is set, to make sure
            // there are no patient-specific documents showing stale data.  If a frame
            // was just loaded with data for the correct patient, its name is passed so
            // that it will not be zapped.  At this point the new server-side pid is not
            // assumed to be set, so this function will only load global data.
            function reloadPatient(frname) {
                var f = document.forms[0];
                if (topName.length > 3 && topName.substring(3) > '0' && frname != 'RTop') {
                    loadFrame('cal0', 'RTop', '<?php echo $primary_docs['cal'][2]; ?>');
                    setRadio('rb_top', 'cal');
                }
                if (botName.length > 3 && botName.substring(3) > '0' && frname != 'RBot') {
                    loadFrame('ens0', 'RBot', '<?php echo $primary_docs['ens'][2]; ?>');
                    setRadio('rb_bot', 'ens');
                }
            }

            // Reload encounter-specific frames, excluding a specified frame.  At this
            // point the new server-side encounter ID may not be set and loading the same
            // document for the new encounter will not work, so load patient info instead.
            function reloadEncounter(frname) {
                var f = document.forms[0];
                if (topName.length > 3 && topName.substring(3) > '1' && frname != 'RTop') {
                    loadFrame('dem1', 'RTop', '<?php echo $primary_docs['dem'][2]; ?>');
                    setRadio('rb_top', 'dem');
                }
                if (botName.length > 3 && botName.substring(3) > '1' && frname != 'RBot') {
                    loadFrame('ens1', 'RBot', '<?php echo $primary_docs['ens'][2]; ?>');
                    setRadio('rb_bot', 'ens');
                }
            }

            // Clear and reload issue-related menu items for active_pid.
            // Currently this only applies to athletic teams, but might be implemented
            // in the general menu at some future time.
            //
            function reloadIssues() {
<?php
if ($GLOBALS['athletic_team']) {
    // Generates a menu item for each active issue that this patient
    // has of each issue type.  Each one looks like this:
    //   Onset-Date [Add] Issue-Title
    // where the first part is a link to open the issue dialog,
    // [Add] is a link that auto-creates and opens a new encounter, and
    // Issue-Title is a link that shows related encounters.
    foreach ($ISSUE_TYPES as $key => $value) {
        ?>
                        $('#icontainer_<?php echo $key ?>').empty();
                        if (active_pid != 0) {
                            $('#icontainer_<?php echo $key ?>').append("<li>" +
                                    "<a href='' id='xxx1' onclick='return repPopup(" +
                                    "\"../patient_file/summary/add_edit_issue.php?thistype=" +
                                    "<?php echo $key; ?>\")' " +
                                    "title='<?php echo xl('Create new issue'); ?>'>" +
                                    "<?php echo xl('New') . " " . $value[1]; ?></a></li>");
                            top.restoreSession();
                            $.getScript('../../library/ajax/left_nav_issues_ajax.php?type=<?php echo $key; ?>');
                        }
        <?php
    }
}
?>
            } // end function reloadIssues

            // This is referenced in left_nav_issues_ajax.php and is called when [Add]
            // is clicked for an issue menu item to add a new encounter for the issue.
            // So far this only applies to the Athletic Team version of the menu.
            //
            function addEncNotes(issue) {

                // top.restoreSession();
                // $.getScript('../../library/ajax/left_nav_encounter_ajax.php?createvisit=1&issue=' + issue);

                // The above AJAX call was to create the encounter right away, but we later
                // (2012-07-03) decided it's better to present the New Encounter form instead.
                // Note the issue ID is passed so it will be pre-selected in that form.
                ajaxRequest('nen1', 'RBot', 'forms/newpatient/new.php?autoloaded=1&calenc=&issue=' + issue);

                return false;
            }

            function loadCurrentPatientFromTitle() {
                top.frames['RTop'].location = '../patient_file/summary/demographics.php';
            }

            function getEncounterTargetFrame(name) {
                var bias = <?php echo $primary_docs['enc'][1] ?>;
                var f = document.forms[0];
                var r = 'RTop';
                if (f.cb_top.checked && f.cb_bot.checked) {
                    if (bias == 2) {
                        r = 'RBot';
                    } else {
                        r = 'RTop';
                    }
                } else {
                    if (f.cb_top.checked) {
                        r = 'RTop';
                    } else if (f.cb_bot.checked) {
                        r = 'RBot';
                    }
                }
                return r;
            }

            function loadCurrentEncounterFromTitle() {
                top.frames[ parent.left_nav.getEncounterTargetFrame('enc') ].location = '../patient_file/encounter/encounter_top.php';
            }

            // You must call this if you delete the active patient (or if for any other
            // reason you "close" the active patient without opening a new one), so that
            // the appearance of the navigation frame will be correct and so that any
            // stale content will be reloaded.
            function clearPatient() {
                if (active_pid == 0)
                    return;
                var f = document.forms[0];
                active_pid = 0;
                active_encounter = 0;
                setDivContent('current_patient', '<b><?php xl('None', 'e'); ?></b>');
                setTitleContent('current_patient', '<b><?php xl('None', 'e'); ?></b>');
                top.window.parent.Title.document.getElementById('past_encounter').innerHTML = '';
                top.window.parent.Title.document.getElementById('current_encounter').innerHTML = "<b><?php echo htmlspecialchars(xl('None'), ENT_QUOTES) ?></b>";
                reloadPatient('');
                syncRadios();
            }

            // You must call this if you delete the active encounter (or if for any other
            // reason you "close" the active encounter without opening a new one), so that
            // the appearance of the navigation frame will be correct and so that any
            // stale content will be reloaded.
            function clearEncounter() {
                if (active_encounter == 0)
                    return;
                top.window.parent.Title.document.getElementById('current_encounter').innerHTML = "<b><?php echo htmlspecialchars(xl('None'), ENT_QUOTES) ?></b>";
                active_encounter = 0;
                reloadEncounter('');
                syncRadios();
            }
            function removeOptionSelected(EncounterId)
            {//Removes an item from the Encounter drop down.
                var elSel = top.window.parent.Title.document.getElementById('EncounterHistory');
                var i;
                for (i = elSel.length - 1; i >= 2; i--) {
                    EncounterHistoryValue = elSel.options[i].value;
                    EncounterHistoryValueArray = EncounterHistoryValue.explode('~');
                    if (EncounterHistoryValueArray[0] == EncounterId) {
                        elSel.remove(i);
                    }
                }
            }

            // You can call this to make sure the session pid is what we expect.
            function pidSanityCheck(pid) {
                if (pid != active_pid) {
                    alert('Session patient ID is ' + pid + ', expecting ' + active_pid +
                            '. This session is unstable and should be abandoned. Do not use ' +
                            'SAC in multiple browser windows!');
                    return false;
                }
                return true;
            }

            // You can call this to make sure the session encounter is what we expect.
            function encounterSanityCheck(eid) {
                if (eid != active_encounter) {
                    alert('Session encounter ID is ' + eid + ', expecting ' + active_encounter +
                            '. This session is unstable and should be abandoned. Do not use ' +
                            'SAC in multiple browser windows!');
                    return false;
                }
                return true;
            }

            // Pop up a report.
            function repPopup(aurl) {
                top.restoreSession();
                window.open('<?php echo "$web_root/interface/reports/" ?>' + aurl, '_blank', 'width=750,height=550,resizable=1,scrollbars=1');
                return false;
            }

            // This is invoked to pop up some window when a popup item is selected.
            function selpopup(selobj) {
                var i = selobj.selectedIndex;
                var opt = selobj.options[i];
                if (i > 0) {
                    var width = 750;
                    var height = 550;
                    if (opt.text == 'Export' || opt.text == 'Import') {
                        width = 500;
                        height = 400;
                    }
                    else if (opt.text == 'Refer') {
                        width = 700;
                        height = 500;
                    }
                    dlgopen(opt.value, '_blank', width, height);
                }
                selobj.selectedIndex = 0;
            }

        </script>

    </head>

    <body class="body_nav">

        <form method='post' name='find_patient' target='RTop'
              action='<?php echo $rootdir ?>/main/finder/patient_select.php'>

            <div class="wrapper-menu cyan-menu">
                <div class="top-holder">
                    <div class="full_width">
					
					
                        <div class="meta2" style="float: left;" id="metalic">
                            <ul>
                                <li style="list-style: none outside none; float: left;display:none;" id="current_patient_block">
                                    <span style="color: rgb(255, 255, 255);"><i class="icon-star"></i> <?php xl('Patient', 'e'); ?> actual:&nbsp;</span><span class='title_bar_top' id="current_patient"><b style="color: rgb(238, 238, 238);"><?php xl('None', 'e'); ?></b></span>
                                </li>
                                <li style="list-style: none outside none; float: left; margin-left: 6px; margin-top: -2px;display:none;" id="past_encounter_block">
                                    <span class='title_bar_top' id="past_encounter"><b><?php echo htmlspecialchars(xl('None'), ENT_QUOTES) ?></b></span>
                                </li>
                                <li style='display:none' id="current_encounter_block">
                                    <span><?php xl('Selected Encounter', 'e'); ?>:&nbsp;</span><span class='title_bar_top' id="current_encounter"><b><?php xl('None', 'e'); ?></b></span>
                                </li>
                            </ul>
                        </div>		
					
                        <div class="meta">
                            <ul>
                                <?php if (!acl_check('admin', 'adm_cnf')){ ?>
                                <li><a href="" onclick="return ajaxRequest('new0', 'RTop', 'new/new.php')" id="new0"><i class="icon-plus-sign"></i> <span>Nuevo paciente</span></a></li>
                                <?php } ?>
                                <li><a href="<?php echo $rootdir ?>/usergroup/user_admin.php?id=<?php echo $provider_session_id ?>&pc_facility=<?php echo $provider_facility_id?>" id="profile" class="fancybox.iframe"><i class="icon-gears"></i> <span>Configuraci&oacute;n</span></a></li>
                                <li><a href="../logout.php?auth=logout" target="_top" id="logout_link"> <i class="icon-signout"></i> <?php echo htmlspecialchars(xl('Logout'), ENT_QUOTES) ?></a></li>
                            </ul>
                        </div>		
                    </div>
                </div><!--/ top-holder-->   
                <div class="bg-menu">
                    <div class="full_width">
                        <div class="logo">
                            <h1><a href="#"><img width="177px" src="../../images/sac.png" height="67px"></a></h1>
                        </div>
                        <ul class="menu">
						<?php if(acl_check('mdls', 'bsqdrpd')) { ?>
                            <li>
                                <a onclick="return ajaxRequest('new0', 'RTop', 'main/finder/dynamic_finder.php')" id="paciente" href="#">B&uacute;squeda r&aacute;pida</a>
                                <!--
                                <a id="paciente" href="#">Pacientes</a>
                                <div class="drop_fourth">
                                        <div class="col sep">
                                                <h3>Paciente</h3>
                                                <ul class="list">
<?php genMiscLink2('RTop', 'new', '0', xl('Patients'), 'main/finder/dynamic_finder.php'); ?>
<?php genTreeLink2('RTop', 'new', ($GLOBALS['full_new_patient_form'] ? xl('New/Search') : xl('New'))); ?>
<?php genTreeLink2('RTop', 'dem', xl('Summary')); ?>
                                                </ul>
                                        </div>
                                        <div class="col sep">
                                                <h3><?php xl('Visits', 'e') ?></h3>
                                                <ul class="list">
                                <?php if ($GLOBALS['ippf_specific'] && !$GLOBALS['disable_calendar']) genTreeLink2('RTop', 'cal', xl('Calendar')); ?>
<?php genTreeLink2('RBot', 'nen', xl('Create Visit')); ?>
<?php genTreeLink2('RBot', 'enc', xl('Current')); ?>
<?php genTreeLink2('RBot', 'ens', xl('Visit History')); ?>
                                                </ul>
                                        </div>
                                        <div class="col sep">
                                                <h3><?php xl('Records', 'e') ?></h3>
                                                <ul class="list">
                                <?php genTreeLink2('RTop', 'prq', xl('Patient Record Request')); ?>
                                                </ul>
                                        </div>
                                <?php if ($GLOBALS['gbl_nav_visit_forms']) { ?>
                                                            <div class="col_last">
                                                                    <h3><?php xl('Visit Forms', 'e') ?></h3>
                                                                    <ul class="list">
                                    <?php
                                    // Generate the items for visit forms, both traditional and LBF.
                                    //
								$lres = sqlStatement("SELECT * FROM list_options " .
                                            "WHERE list_id = 'lbfnames' ORDER BY seq, title");
                                    if (sqlNumRows($lres)) {
                                        while ($lrow = sqlFetchArray($lres)) {
                                            $option_id = $lrow['option_id']; // should start with LBF
                                            $title = $lrow['title'];
                                            genMiscLink2('RBot', 'cod', '2', xl_form_title($title), "patient_file/encounter/load_form.php?formname=$option_id");
                                        }
                                    }
                                    include_once("$srcdir/registry.inc");
                                    $reg = getRegistered();
                                    if (!empty($reg)) {
                                        foreach ($reg as $entry) {
                                            $option_id = $entry['directory'];
                                            $title = trim($entry['nickname']);
                                            if ($option_id == 'fee_sheet')
                                                continue;
                                            if ($option_id == 'newpatient')
                                                continue;
                                            if (empty($title))
                                                $title = $entry['name'];
                                            genMiscLink2('RBot', 'cod', '2', xl_form_title($title), "patient_file/encounter/load_form.php?formname=" .
                                                    urlencode($option_id));
                                        }
                                    }
                                    ?>
                                                                    </ul>
                                                            </div>
<?php } // end if gbl_nav_visit_forms   ?>						
                                </div>
                                -->
                            </li>
							<?php }?>
							<?php if(acl_check('mdls', 'pcnts')) { ?>
                            <li>
                                <a id="admision" onclick="return ajaxRequest('new0', 'RTop', 'new/new.php')" id="new0" href="">Pacientes</a>
                            </li>
							<?php }?>
							
							<?php if(acl_check('mdls', 'inout_box')) { ?>
	<li><a id="mail" href="#">Mensajeria</a>
		
		<ul class="levels">
			<li>
				<?php genMiscLink2('RTop', 'msg', '0', 'Recordatorios y Mensajes', 'main/messages/messages.php?form_active=1'); ?>
				<?php echo $element; ?>
			</li>
			<!--li>
				<?php genMiscLink2('RTop', 'rep', '0', 'Comunicacion en serie', 'batchcom/batchcom.php'); ?>
			</li-->
			<!--li>
				<?php genMiscLink2('RTop', 'rep', '0', 'Reglas', 'super/rules/index.php?action=browse!list'); ?>
			</li>
			<li>
				<?php genMiscLink2('RTop', 'rep', '0', 'Alertas', 'super/rules/index.php?action=alerts!listactmgr'); ?>
			</li>
			<li>
				<?php genMiscLink2('RTop', 'rep', '0', 'Recordatorios del paciente', 'patient_file/reminder/patient_reminders.php?mode=admin&patient_id='); ?>
			</li-->
		</ul> 
	</li>
							<?php }?>
							
							<?php if(acl_check('mdls', 'hy')) { ?>
                            <li>
                                <a id="hoy" onclick="return ajaxRequest('cal0', 'RTop', 'main/calendar/index.php?module=PostCalendar&amp;viewtype=day&amp;func=view')" id="cal0" href="">Hoy</a>
                            </li>
							<?php }?>
                            <?php if (!$GLOBALS['disable_calendar'] && !$GLOBALS['ippf_specific'] && acl_check('mdls', 'clndr')) { ?>
                                <li>
                                    <a id="calendario" onclick="return ajaxRequest('cal0', 'RTop', 'main/calendar/index.php?module=PostCalendar&amp;viewtype=month&amp;func=view')" id="cal0" href="">Calendario</a>
                                </li>
							<?php } ?>
							<?php if(acl_check('mdls', 'mdcmnts')) { ?>
							<?php if(acl_check('mdls', 'mdcmnts')) { ?>
<?php } ?>
							<?php } ?>
							<?php if(acl_check('mdls', 'rprts')) { ?>
                            <li><a id="reportes" href="#">Reportes</a>
                                <ul class="levels">  
                                    <?php if(acl_check('admin', 'adm_cnf') ){ ?>
                                    <li><a class="parent" href="#"><?php echo "Estadísticos";?></a>
                                        <ul style='z-index:999'>
                                            <?php genMiscLink2('RTop', 'rep', '0', /*xl('Encounters')*/ "Número de Consultas", 'reports/encounters_report.php'); ?>
                                            <?php genMiscLink2('RTop', 'rep', '0', /*xl('Encounters')*/'Número de Teleconsultas', 'reports/teleconsultas_report.php'); ?>
                                            <?php genMiscLink2('RTop', 'rep', '0', /*xl('Encounters')*/'Número de Derivaciones', 'reports/contrareferencia_report.php'); ?>
                                            <?php genMiscLink2('RTop', 'rep', '0', /*xl('Encounters')*/'Diagnósticos más Frecuentes', 'reports/clinicos_reports.php'); ?>
                                            <?php genMiscLink2('RTop', 'rep', '0', /*xl('Encounters')*/'Apoyos Diagnósticos', 'reports/ordenacion_report.php'); ?>
                                            <?php genMiscLink2('RTop', 'rep', '0', 'Número de Usuarios Atendidos', 'reports/patient_list.php'); ?>
                                            <?php genMiscLink2('RTop', 'rep', '0', /*xl('Encounters')*/'Frecuencias de Remisiones de Pacientes', 'reports/remision_reports.php'); ?>
                                            <?php if (!$GLOBALS['disable_calendar']) genMiscLink2('RTop', 'rep', '0', ' Reporte Detallado de Pacientes Atendidos', 'reports/appt_encounter_report.php'); ?>
                                        </ul>
                                    </li>
                                    <?php } ?>
                                    <li><a class="parent" href="#"><?php xl('Blank Forms', 'e') ?></a>
                                        <ul style='z-index:999'>
                                            <?php genPopLink2(xl('Demographics'), '../patient_file/summary/demographics_print.php'); ?>
                                            <?php genPopLink2(xl('Referral'), '../patient_file/transaction/print_referral.php'); ?>
                                            <?php
                                            $lres = sqlStatement("SELECT * FROM list_options " .
                                                    "WHERE list_id = 'lbfnames' ORDER BY seq, title");
                                            while ($lrow = sqlFetchArray($lres)) {
                                                $option_id = $lrow['option_id']; // should start with LBF
                                                $title = $lrow['title'];
                                                genPopLink2($title, "../forms/LBF/printable.php?formname=$option_id");
                                            }
                                            ?>
                                        </ul>
                                    </li>
                                    
                                 
                                          
                                       
                                </ul> 
                            </li>
							<?php } ?>
                        </ul><!--/ menu-->
                    </div><!--/ full_width-->
                    <div class="clear"></div>	    
                </div><!--/ bg-menu--> 
            </div><!--/ wraper-menu-->
        </form>
        <form>
            <input type="hidden" name="authUser" id="authUser" value="<?php
            if (isset($_REQUEST['authUser']))
                echo $_REQUEST['authUser'];
            else
                echo '';
            ?>"/>
            <input type="hidden" name="destino" id="destino" value="<?php
            if (isset($_REQUEST['destino']))
                echo $_REQUEST['destino'];
            else
                echo '';
            ?>"/>
            <input type="hidden" name="pname" id="nombre" value="<?php
            if (isset($_REQUEST['pname']))
                echo $_REQUEST['pname'];
            else
                echo '';
            ?>"/>
            <input type="hidden" name="pid" id="pacienteId" value="<?php
            if (isset($_REQUEST['pid']))
                echo $_REQUEST['pid'];
            else
                echo '';
            ?>"/>
            <input type="hidden" name="pubpid" id="identificacion" value="<?php
                   if (isset($_REQUEST['pubpid']))
                       echo $_REQUEST['pubpid'];
                   else
                       echo '';
                   ?>"/>
        </form>
    </body>
</html>
